package com.ffmpeg;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Utils {
    static void copyFile(File inputFile, File outputFile) throws IOException{
        InputStream input = new FileInputStream(inputFile);
        OutputStream output = new FileOutputStream(outputFile);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
            output.write(buffer, 0, bytesRead);
        }
        output.flush();
        output.close();
        input.close();
    }

    public static void downLoadFile(String url, String dir, DownloadStatus downloadStatus) {
        new OkHttpClient().newCall(new Request.Builder().url(url).build()).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                downloadStatus.error(e);
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                File file = new File(dir);
                OutputStream outputStream = null;
                InputStream inputStream = response.body().byteStream();
                try {
                    outputStream = new FileOutputStream(file);
                    int len = 0;
                    byte[] buffer = new byte[1024*10];
                    while ((len = inputStream.read(buffer))!=-1){
                        outputStream.write(buffer,0,len);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        inputStream.close();
                        if(outputStream != null)
                            outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    downloadStatus.finish(dir);
                }
            }
        });
    }
    public interface DownloadStatus {
        void finish(String dir);
        void error(IOException e);
    }
    public static <T> T[] concat(T[] a, T[] b) {
        int aLen = a.length;
        int bLen = b.length;
        @SuppressWarnings("unchecked")
        T[] c = (T[]) Array.newInstance(Objects.requireNonNull(a.getClass().getComponentType()), aLen + bLen);
        System.arraycopy(a, 0, c, 0, aLen);
        System.arraycopy(b, 0, c, aLen, bLen);
        return c;
    }

}
